'use strict';

const urlJoin = require('url-join')
const semver = require('semver')
const axios = require('axios')
const log = require('@cli-dev/log')

 async function getNpmInfo(npmName, registry) {
    if(!npmName){
        return null
    }
    let registryUrl = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(registryUrl, npmName)
    log.verbose('npmInfoUrl==222',npmInfoUrl,)
    return axios.get(npmInfoUrl).then(response=> {
        if(response.status===200){
          return response.data
        }
        return null
    }).catch(err=> {
        Promise.reject(err)
    })
}

function getDefaultRegistry(isOriginal = false){
    return isOriginal ? 'https://registry.npmjs.org' :'https://registry.npm.taobao.org/'
}


async function getNpmVersions(npmName, registry){
    const data = await getNpmInfo(npmName, registry)
    console.log('getNpmVersions====1111',npmName)
    if(data){
        return Object.keys(data.versions)
    }else {
        return []
    }

}

// 获取满足要求的npm版本号
function getSemverVersion(baseVersion, versions){
    return  versions
    .filter(version => semver.satisfies(version, `^${baseVersion}`))
    .sort((a, b) => semver.compare(b,a)); // 自己重新排序一下，防止从接口返回的不是已经排序好的
    
}

async function getNpmSemverVersion(baseVersion,npmName, registry ){
    const versions = await getNpmVersions(npmName, registry)
    const newVersion = getSemverVersion(baseVersion, versions)
    console.log()
    if(newVersion && newVersion.length > 0){
        return newVersion[0]
    }
    return null

}

async function getNpmLatestVersion(npmName, registry) {
    let versions = await getNpmVersions(npmName, registry);
    if (versions) {
      return versions.sort((a, b) => semver.gt(b, a))[0];
    }
    return null;
  }
  

module.exports = {
    getNpmInfo,
    getNpmVersions,
    getNpmSemverVersion,
    getDefaultRegistry,
    getNpmLatestVersion
};
